const { warn } = require("../utils/log_tool");
const { format, toArray } = require("../utils/transform_tool");
const { BaseCommand } = require("./base");

class EditCommand extends BaseCommand {
    async execute() {
        const content = this.content;
        /**
         * @type { {type: string, data: any}[] }
         */
        let actions = this.selfData.actions;
        if (typeof actions === "string") {
            // delete group,update group 6599,update ios_pay true,delete ios_pay
            actions = actions
                .split(",")
                .filter(Boolean)
                .map((action) => {
                    const hashIdx = action.indexOf("#");
                    let desc = "";
                    if (hashIdx >= 0) {
                        desc = action.substring(hashIdx + 1);
                        action = action.substring(0, hashIdx);
                    } else {
                        desc = action;
                    }
                    const [type, prop, val] = action.split(" ");
                    switch (type) {
                        case "delete": {
                            return { type, desc, data: { [prop]: true } };
                        }
                        case "update": {
                            return { type, desc, data: { [prop]: eval(val) } };
                        }
                    }
                })
                .filter((v) => v);
        }
        actions.forEach((action) => {
            const actionType = action.type;
            const actionData = action.data;
            const _actionDesc = action.desc;
            switch (actionType) {
                case "delete": {
                    if (Array.isArray(actionData)) {
                        actionData.forEach((key) => {
                            delete content[key];
                        });
                    } else if (typeof actionData === "object") {
                        Object.keys(actionData).forEach((key) => {
                            if (actionData[key]) {
                                delete content[key];
                            }
                        });
                    } else {
                        warn(`未支持的 edit - delete 参数`);
                    }
                    break;
                }
                case "update": {
                    for (const key in actionData) {
                        content[key] = actionData[key];
                    }
                    break;
                }
                default: {
                    warn(`未支持的 edit 类型 ${actionType}`);
                    break;
                }
            }
        });
        return actions;
    }

    getRequireContent() {
        return true;
    }

    getRequiredParams() {
        return ["actions"];
    }
}

module.exports = {
    EditCommand,
};
